import user from "../api/user";
import dr from "../router/Dynamically";


export default {
    strict: true,
    namespaced: true,
    state() {
        return {
            userInfo: undefined,
            roles: [],
            routes: []
        }
    },
    mutations: {
        m_userInfo(state, payload) {
            state.userInfo = payload
        },
        m_roles(state, payload) {
            state.roles = payload
        },
        m_routes(state, payload) {
            state.routes = payload
        }
    },
    actions: {
        GetUserInfo(store) {
            return new Promise(resolve => {
                // 登录状态存在
                if (store.state.userInfo) {
                    resolve(store.state.userInfo)
                } else
                    user.GetUserInfo().then(r => {
                        // 获取用户登录状态信息
                        if (r.data.status === "200" && r.data.data.msg !== 'token过期') {
                            if (r.data.data.admin !== "true") {
                                store.commit("m_userInfo", r.data.data.user)
                                // 学生用户
                                // const routes = dr.FileterRoutes(dr.dynamically, ["user"], true)
                                // dr.addRoutes(routes, 'index')
                                // store.commit("m_roles", ["user"])
                                // store.commit("m_routes", routes)
                                setStore(store, ["user"])
                            } else {
                                store.commit("m_userInfo", r.data.data.adminUser)
                                // 管理员用户
                                setStore(store, r.data.data.adminUser.role)
                            }
                        }
                        // 得到登录状态
                        resolve(store.state.userInfo)
                    })
            })
        }
    },
    getters: {
        roles: state => {
            return state.roles
        },
        userInfo: state => {
            return state.userInfo
        }
    }
}

function setStore(store, roles) {
    const routes = dr.FileterRoutes(dr.dynamically, roles, true)
    dr.addRoutes(routes, 'index')
    store.commit("m_roles", roles)
    store.commit("m_routes", routes)
}